#!/usr/bin/env bash

build_cunumeric_conda_package() {
    set -xeuo pipefail;

    local python_version="${PYTHON_VERSION:-}";

    if [ -z "${python_version}" ]; then
        python_version="$(python3 --version 2>&1 | cut -d' ' -f2 | cut -d'.' -f3 --complement)";
    fi

    mkdir -p /tmp/conda-build /tmp/out
    cp -r ~/.artifacts/legate_core /tmp/conda-build/

    local conda_build_args=();
    conda_build_args+=(--override-channels);
    conda_build_args+=(-c conda-forge);
    conda_build_args+=(-c nvidia);
    conda_build_args+=(-c file:///tmp/conda-build/legate_core);
    conda_build_args+=(--croot /tmp/conda-build/cunumeric);
    conda_build_args+=(--numpy 1.22);
    conda_build_args+=(--python ${python_version});
    conda_build_args+=(--no-test);
    conda_build_args+=(--no-verify);
    conda_build_args+=(--no-build-id);
    conda_build_args+=("--build-id-pat=''");
    conda_build_args+=(--no-include-recipe);
    conda_build_args+=(--no-anaconda-upload);

    GPU_ENABLED=true
    [ "${USE_CUDA:-}" = "OFF" ] && GPU_ENABLED=false

    conda_build_args+=(--variants "{gpu_enabled:${GPU_ENABLED},python:${python_version}}");

    rm -rf /tmp/conda-build/cunumeric;
    mkdir -p /tmp/conda-build/cunumeric;

    # Synthesize new cunumeric conda-build build.sh script

    cat <<EOF > ~/cunumeric/conda/conda-build/conda_build_config.yaml
gpu_enabled:
  - "${GPU_ENABLED}"

python:
  - "${python_version}"

numpy_version:
  - ">=1.22"

cmake_version:
  - ">=3.20.1,!=3.23.0"

use_local_path:
  - "true"

numpy:
  - 1.22

package_version:
  - "$(git -C ~/cunumeric describe --abbrev=0 --tags | sed 's/[a-zA-Z]//g' | cut -d '.' -f -2).00"
EOF

    cat <<"EOF" > ~/cunumeric/conda/conda-build/build.sh
# Install cunumeric C++ libs
tar -C "$PREFIX" --exclude="*.a" --strip-components=1 -xvf /tmp/out/cunumeric-*-Linux.tar.gz;

# Install cunumeric Python wheel
pip install --no-deps --root / --prefix "$PREFIX" /tmp/out/cunumeric-*.whl;
EOF

    git -C ~/cunumeric add .;
    git -C ~/cunumeric commit --allow-empty --allow-empty-message -n -m "";

    # Build cuNumeric conda package
    CUDA=${CUDA_VERSION_MAJOR}.${CUDA_VERSION_MINOR} \
    conda mambabuild ${conda_build_args[@]} ~/cunumeric/conda/conda-build;

    git -C ~/cunumeric reset --hard HEAD~1;

    cp /tmp/conda-build/cunumeric/linux-64/cunumeric-*.tar.bz2 /tmp/out/;

    { set +x; } 2>/dev/null;
}

(build_cunumeric_conda_package "$@");
